% ---------------------------------------------------
% @doc 用户信息处理器.
% ---------------------------------------------------
-module(user_handler).

-include("cloap_record.hrl").

-export([init/2]).
-export([
  allowed_methods/2,
  content_types_accepted/2,
  resource_exists/2
]).

-export([
  create/2
]).


init(Req, Opts) ->
	{cowboy_rest, Req, Opts}.

allowed_methods(Req, State) ->
  {
    [<<"GET">>, <<"POST">>, <<"HEAD">>, <<"OPTIONS">>],
    Req, State
  }.


content_types_accepted(Req, State) ->
    {[
      {<<"text/plain;charset=UTF-8">>, create}
     ],
     Req, State}.



resource_exists(Req, _State) ->
    {true, Req, index}.



create(Req, State) ->
    {ok, Body, Req2} = cowboy_req:body(Req),
    Params = jsx:decode(Body),

    [Login, Password, Name] = 
        [ proplists:get_value(list_to_binary(X), Params) || X <- ["login", "password", "name"] ],
 
    case cloap_store:find(user, {login, Login}) of
        not_found ->
            cloap_store:insert(#user{id = cloap_store:uuid(), login = Login, passwd = Password, name = Name});
        Rec ->
            cloap_store:update(Rec#user{ passwd = Password, name = Name })
    end,
    update_user_password(Login, Params),

    Req3 = cowboy_req:set_resp_body(jsx:encode(Params), Req2),
    {true, Req3, State}.



update_user_password(Login, Params) ->
    case user_store:find_one(Login) of
        not_found ->
            cloap_handler:handle("user.create", Params);
        _ ->
            cloap_handler:handle("user.reset.password", Params)
    end.
